<template>
  <el-dialog
    title="药品配送信息确认"
    :visible="visible"
    @update:visible="onVisibleChange"
    append-to-body
    :close-on-click-modal="false"
    custom-class="cloud-delivery-check"
    :width=" isAddingAddress ? '720px' : '1000px'">
    <el-form
      size="small"
      :model="deliveryForm"
      label-width="90px"
      ref="deliveryForm"
      v-if="!isAddingAddress">
      <el-alert
        v-if="!isAddingAddress"
        title="订单可能会产生运费。请根据医院规定，告知用户！"
        show-icon
        :closable="false"
        type="warning"
        style="margin-bottom: 20px;">
      </el-alert>
      <el-form-item label="配送药房" required prop="pharmacyId">
        <el-select placeholder="请选择药房" v-model="deliveryForm.pharmacyId">
          <el-option
            v-for="store in drugStoreList"
            :key="store.id"
            :value="store.id"
            :label="store.name"
          />
        </el-select>
      </el-form-item>
       <el-form-item label="配送地址" required>
        <div class="delivery-address-list" v-if="displayAddressList.length > 0">
          <p><span @click="onAddClick"><i class="el-icon-plus"></i>新增地址</span></p>
          <el-table
            size="large"
            :data="displayAddressList"
            border
            v-loading="fetching"
            style="width: 100%;">
            <el-table-column width="50">
              <template slot-scope="{ row }">
                <el-radio v-model="deliveryForm.addressId" :label="row.addressId">{{''}}</el-radio>
              </template>
            </el-table-column>
            <el-table-column
              prop="contactName"
              label="姓名"
              width="170">
            </el-table-column>
            <el-table-column
              prop="contactTelephone"
              label="电话"
              width="170">
            </el-table-column>
            <el-table-column prop="address" label="地址">
              <template slot-scope="{ row }">
                <el-tag type="danger" v-if="row.isDefault" style="margin-left: 10px; border-radius: 30px; float: right;">默认地址</el-tag>
                <div style="margin-right: 70px;">
                  {{getComplateAddress(row)}}
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="addressList.length > 6">
            <div v-if="!showMore" @click="showMore = true" class="more-action"> 更多地址<i class="el-icon-arrow-down"></i></div>
            <div v-else @click="showMore = false" class="more-action">收起<i class="el-icon-arrow-up"></i></div>
          </div>
        </div>
        <WeDataBlank noBorder type="new" v-else>
          <div style="color: #8C9AB4;">暂无配送地址 <span class="link-button" @click="onAddClick">去新增 <i class="el-icon-arrow-right"></i> </span></div>
        </WeDataBlank>
      </el-form-item>
    </el-form>
    <!-- 新增地址 -->
    <el-form
      size="small"
      v-else
      :model="newAddresssForm"
      label-width="90px"
      class="new-address-form"
      ref="newAddresssForm"
      :rules="rules">
      <el-form-item label="姓名" prop="contactName">
        <el-input
          placeholder="请输入姓名"
          v-model="newAddresssForm.contactName">
        </el-input>
      </el-form-item>
      <el-form-item label="电话" prop="contactTelephone">
        <el-input
          placeholder="请输入电话"
          v-model="newAddresssForm.contactTelephone">
        </el-input>
      </el-form-item>
      <el-form-item label="地址信息" prop="areaCodes">
        <WeAddress v-model="newAddresssForm.areaCodes" placeholder="请选择地址">
        </WeAddress>
      </el-form-item>
      <el-form-item label="详细地址" prop="street">
        <el-input v-model="newAddresssForm.street">
        </el-input>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-bunch>
      <el-button
        type="primary"
        @click="onAddNewAddress"
        v-if="isAddingAddress">
        保存
      </el-button>
      <el-button
        class="btn-fun-blue"
        type="primary"
        @click="onSubmit"
        v-else>
        提交
      </el-button>
      <el-button
        @click="onCancel">
        取消
      </el-button>
      </el-bunch>
    </div>
  </el-dialog>
</template>
<script>
import clinicApi from '@/services/clinic';
import WeAddress from '@/components/form/we-address';
import WeDataBlank from '@/components/base/we-data-blank';
import patterns from '@/utils/patterns';

const rules = {
  contactName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
    // { max: 2, message: '长度在 3 到 5 个字符', trigger: 'blur' }
  ],
  contactTelephone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: patterns.mobile, message: '请输入正确的电话号码格式', trigger: 'blur' }
  ],
  areaCodes: [
    { required: true, message: '请选择地区', trigger: 'change' }
  ],
  street: [
    { required: true, message: '请填入详细地址', trigger: 'change' }
  ]
};

export default {
  components: {
    WeAddress,
    WeDataBlank
  },
  props: {
    visible: {
      default: false,
      type: Boolean
    },
    drugIds: {
      default: () => [],
      type: Array
    },
    type: {
      type: [String, Number],
      default: 1
    }
  },
  data () {
    return {
      rules,
      isAddingAddress: false,
      drugStoreList: [],
      addressList: [],
      deliveryForm: {
        addressId: '',
        pharmacyId: ''

      },
      fetching: false,
      showMore: false,
      // 用来存刚刚新建好的addressId
      newAddressId: '',
      newAddresssForm: {
        contactName: '',
        contactTelephone: '',
        areaCodes: '',
        street: ''
      }
    };
  },
  computed: {
    displayAddressList () {
      return this.showMore ? this.addressList : this.addressList.slice(0, 6);
    }
  },
  watch: {
    visible (val) {
      if (val) {
        this.fetchDeliveryInfo();
      }
    },
    isAddingAddress (val) {
      this.$nextTick(() => {
        if (val) {
          this.newAddresssForm = {
            contactName: '',
            contactTelephone: '',
            areaCodes: '',
            street: ''
          };
          this.$refs.newAddresssForm.clearValidate();
        } else {
          this.$refs.deliveryForm.clearValidate();
        }
      });
    }
  },
  methods: {
    fetchDeliveryInfo () {
      const params = {
        visitId: this.$route.params.visitId,
        drugIds: this.drugIds.join(','),
        type: this.type
      };
      this.fetching = true;
      Promise.all([
        clinicApi.apiGetCloudPharmacyList(params),
        clinicApi.apiGetUserAddressList({
          patientId: this.$route.params.patientId
        })
      ]).then(([pharmacyList = [], addressList = []]) => {
        this.drugStoreList = pharmacyList;
        if (this.drugStoreList.length > 0) {
          this.deliveryForm.pharmacyId = this.drugStoreList[0].id;
        }

        const sortAddressList = addressList.sort((addr, anotherAddr) => {
          if (addr.isDefault) {
            return -1;
          }

          if (anotherAddr.isDefault) {
            return 1;
          }

          if (addr.addressId === this.newAddressId) {
            return -1;
          }

          if (anotherAddr.addressId === this.newAddressId) {
            return 1;
          }
        });

        this.addressList = sortAddressList;
        if (this.newAddressId) {
          this.deliveryForm.addressId = this.newAddressId;
          return;
        }
        const defaultAddress = this.addressList.find(({ isDefault }) => !!isDefault);
        this.deliveryForm.addressId = defaultAddress.addressId;
      }).finally(() => {
        this.fetching = false;
      });
    },

    onAddClick () {
      this.newAddresssForm = {
        contactName: '',
        contactTelephone: '',
        areaCodes: '',
        street: ''
      };
      this.isAddingAddress = true;
    },

    getComplateAddress (address = {}) {
      return `${address.provinceName}${address.cityName || ''}${address.areaName || ''}${address.street || ''}`;
    },

    onAddNewAddress () {
      this.$refs.newAddresssForm.validate(res => {
        if (!res) {
          return;
        }
        const { areaCodes, ...params } = this.newAddresssForm;
        const [provinceCode, cityCode, areaCode] = areaCodes;
        clinicApi.apiPostSaveUserAddress({
          ...params,
          provinceCode,
          cityCode,
          areaCode,
          patientId: this.$route.params.patientId
        }).then((newAddressId) => {
          this.newAddressId = newAddressId;
          this.$message.success('地址新增成功！');
          this.isAddingAddress = false;
          this.fetchDeliveryInfo();
        });
      });
    },

    onCancel () {
      if (this.isAddingAddress) {
        this.isAddingAddress = false;
        return;
      }

      this.onVisibleChange(false);
    },

    onSubmit () {
      const pharmacyName = (this.drugStoreList.find(({ id }) => +id === +this.deliveryForm.pharmacyId) || {}).name;
      const delivery = this.addressList.find(({ addressId }) => this.deliveryForm.addressId === addressId);
      this.$emit('submit', {
        ...delivery,
        pharmacyName,
        pharmacyId: this.deliveryForm.pharmacyId,
        contactAddress: this.getComplateAddress(delivery)
      });
    },

    onVisibleChange (v) {
      this.$emit('update:visible', v);
    }
  }
};
</script>
<style lang="less">
  .cloud-delivery-check {
    .link-button {
      color: #3e7fee;
      cursor: pointer;
    }
    .el-alert--warning {
      margin-bottom: 20px;
      background: #FFF7EB;
      color: #FF9400;
      .el-icon-warning {
        color: #FFAD3B;
      }
    }

    .el-form-item__label {
      padding-right: 16px;
    }

    .el-select.el-select--small {
      width: 100%;
    }

    .el-table {
      &__body-wrapper {
        overflow: hidden;
      }
      th, td {
        line-height: 29px;
        padding: 4px 0;
      }
    }
    .delivery-address-list {
      .el-table--border td:first-child .cell {
        text-align: center;
      }
      .more-action {
        text-align: center;
        color: #3E7FEE;
        cursor: pointer;
        line-height: 16px;
        padding-top: 16px;
      }
      .el-radio__label {
        display: none;
      }
      >p {
        text-align: right;
        span {
          cursor: pointer;
          color: #3E7FEE;
        }
      }
    }
    .address-select {
      .el-button {
        float: right;
      }
      .el-select.el-select--small {
        width: auto;
        display: block;
        margin-right: 110px;
      }
    }

    .new-address-form {
      .el-input__inner {
        border: 1px solid #C1C9D7;
      }
    }

    .we-data-blank {
      padding: 30px 0;
    }
  }
</style>
